package org.example.myleet.p703;

import java.util.PriorityQueue;

class KthLargest {

    PriorityQueue<Integer> heap;

    int K;

    /**
     * 21 ms
     * 维护一个k大小的小根堆，堆顶就是第k个最大的值
     */
    public KthLargest(int k, int[] nums) {
        heap = new PriorityQueue<>();
        K = k;
        for (int n : nums) {
            add(n);
        }
    }

    public int add(int val) {
        if (heap.size() < K) {
            heap.offer(val);
        } else {
            if (val > heap.peek()) {
                heap.poll();
                heap.offer(val);
            }
        }
        return heap.peek();
    }
}
